#!/usr/bin/python
# -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: nil; -*-
SOCKS5_PROXY = True
if SOCKS5_PROXY:
    import socks
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,'127.0.0.1',9050)
    import socket
    
    for name in dir(socks):
        setattr(socket,name,getattr(socks,name))
    
    socket.socket = socks.socksocket
    
    #import urllib2
    #handler=urllib2.urlopen('http://sevenever.spaces.live.com')

import codecs
import os.path
import urllib
import urllib2
import cookielib
from xml.dom import minidom

class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler):
    def http_error_default(self, req, fp, code, msg, headers):
        result = urllib2.HTTPError(
            req.get_full_url(), code, msg, headers, fp)       
        result.status = code
        return result
class fetionUser(object):
    def __init__(self):
        self.ssi_app_sign_in = ''
        self.sipc_proxy = ''
        self.http_tunnel = ''
        self.ssic = ''
        self.uri = ''
        self.sid = ''
        self.mobileno = '13764481777'
        self.password = '332335'
class fetionSystemSetting(object):
    def __init__(self):
        self.ssi_app_sign_in = ''
        self.sipc_proxy = ''
        self.http_tunnel = ''
class fetionClient(object):
    def __init__(self,syssetting,user):
        self.syssetting = syssetting
        self.user = user
        self.cj = cookielib.LWPCookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj),DefaultErrorHandler)
        urllib2.install_opener(self.opener)
        self.txheaders =  {'User-agent' : 'IIC2.0/PC 2.1.0.0'}
        
    def getSystemConfig(self):
        theurl = 'http://nav.fetion.com.cn/nav/getsystemconfig.aspx'
        
        txdata = '<config><user mobile-no="13764481777" /><client type="PC" version="2.1.0.0" platform="W5.1" /><servers version="12" /><service-no version="1" /><parameters version="4" /><hints version="4" /><http-applications version="5" /></config>'
        req = urllib2.Request(theurl, txdata, self.txheaders)
        handle = urllib2.urlopen(req)
        strXml = handle.read()
        xmldoc = minidom.parseString(strXml)
        
        self.syssetting.ssi_app_sign_in = xmldoc.childNodes[0].childNodes[0].childNodes[3].firstChild.data
        self.syssetting.ssi_app_sign_in = 'https://221.130.45.201/ssiportal/SSIAppSignIn.aspx'
        
        self.syssetting.sipc_proxy = xmldoc.getElementsByTagName('config')[0].getElementsByTagName('sipc-proxy')[0].firstChild.data
        self.syssetting.http_tunnel =xmldoc.getElementsByTagName('config')[0].getElementsByTagName('http-tunnel')[0].firstChild.data
        self.syssetting.http_tunnel = 'HTTP://221.130.44.193/ht/sd.aspx'
    def ssiLogin(self):
        '''开始执行SSI登录, SSI Url: 
        获取系统配置得到的ssi-app-sign-in'''
        theurl = '%s?mobileno=%s&pwd=%s' % (self.syssetting.ssi_app_sign_in, self.user.mobileno, self.user.password) 
        
        req = urllib2.Request(theurl, None, self.txheaders)
        handle = urllib2.urlopen(req)
        strXml = handle.read()
        #获取ssid
        #<?xml version="1.0" encoding="utf-8" ?><results status-code="200"><user uri="sip:670546214@fetion.com.cn;p=3545" mobile-no="13764481777" user-status="101"><credentials></credentials></user></results>
        self.user.ssic =  self.cj._cookies['221.130.45.201']['/']['ssic'].value
        self.user.uri = minidom.parseString(strXml).getElementsByTagName('user')[0].getAttribute('uri')
        self.user.sid = self.user.uri[self.user.uri.index(':')+1:self.user.uri.index('@')]
        #为http-tunnel设置cookie
        ssihost = urllib.splithost(urllib.splittype(self.syssetting.ssi_app_sign_in)[1])[0]
        hthost = urllib.splithost(urllib.splittype(self.syssetting.http_tunnel)[1])[0]
        cookie = self.cj._cookies[ssihost]['/']['ssic']
        cookie.path = '*'
        cookie.domain = hthost
        self.cj.set_cookie(cookie)
    def registerToSIPC(self):
        #向Proxy Server注册,使用http-tunnel方式，而不是tcp直连8080的方式
        args = '<args><device type=\"PC\" version=\"0\" client-version=\"3.1.0480\" /><caps value=\"fetion-im;im-session;temp-group\" /><events value=\"contact;permission;system-message\" /><user-info attributes=\"all\" /><presence><basic value=\"400\" desc=\"\" /></presence></args>'
        txdata = '\r\n'.join(['R fetion.com.cn SIP-C/2.0',
                              'F: %s' % self.user.sid,
                              'I: 1',
                              'Q: 1 R',
                              'L: %d' % len(args)])
        txdata += '\r\n' + args
        
        req = urllib2.Request(self.syssetting.http_tunnel, txdata, self.txheaders)
        self.handle = urllib2.urlopen(req)
        strXml = self.handle.read()
        print self.handle.status
        print strXml



